<?php

namespace App\Http\Controllers;

use App\Contract\ContractStatus;
use App\Http\Service\ContractService;
use App\Model\Contract;
use App\Model\Fdd;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;

class FddCallbackController
{
    public function message(Request $request)
    {
        $appId = $request->header('X-FASC-App-Id');
        if ($appId != env('FDD_APP_ID')) {
            return '{"msg":"fail"}';
        }
        $event = $request->header('X-FASC-Event');

        $bizContent = $request->input('bizContent');

        $data = json_decode($bizContent, true);
        Log::info('FDD message', [$data]);

        switch ($event) {
            case 'sign-task-signed':
                $this->signTaskSuccess($data);
                break;
            case 'seal-authorize-free-sign':
                $this->corpFreeSign($data);
                break;
            case 'personal-seal-authorize-free-sign':
                $this->personalFreeSign($data);
                break;
        }

        return '{"msg":"success"}';
    }

    public function signTaskSuccess($data)
    {
        $contract = Contract::query()->where('sign_task_id', $data['signTaskId'])->with('contractRent', 'contractTenant')->first();
        if (!$contract) {
            Log::error('合同不存在', [$data]);
            return;
        }
        if ($data['signTaskStatus'] == 'task_finished') {
            $contract->status = ContractStatus::YIQIANYUE;
            $contract->save();
            $contractService = new ContractService();
            $contractService->createBill($contract);
        }
    }

    public function corpFreeSign($data)
    {
        $fdd = Fdd::query()->where('open_user_id', $data['openCorpId'])->first();
        if (!$fdd) {
            Log::error('法大大账号不存在', [$data]);
            return;
        }
        $fdd->seal_id = $data['sealId'];
        $fdd->save();
    }

    public function personalFreeSign($data)
    {
        $fdd = Fdd::query()->where('open_user_id', $data['openUserId'])->first();
        if (!$fdd) {
            Log::error('法大大账号不存在', [$data]);
            return;
        }
        $fdd->seal_id = $data['sealId'];
        $fdd->save();
    }
}
